﻿# -*- coding: utf-8 -*-
# The root HTML has:

import xbmcplugin, xbmcgui, urllib, re, urllib2, string, urlparse, sys
if sys.version_info < (2, 7):
    import simplejson
else:
    import json as simplejson


def error(message):
    addon_id=urlparse.urlsplit(sys.argv[0])[1]
    err_msg='ERROR: %s [%s] ' % (message, addon_id)
    xbmcgui.Dialog().ok('错误', '不好意思，出错了！', err_msg)
    sys.exit(1)


def getPageData(url):
    req=urllib2.Request(urllib.unquote(url))
    try:
        response=urllib2.urlopen(req)
    except:
        error(url + ': URL不能打开')
    data=response.read()
    response.close()
    return data

def getMainMenu(pageData):
    contentList = []
    contentList.append(('电视剧', 'tv/?alt=json'))
    contentList.append(('电影', 'movie/?alt=json'))
    contentList.append(('综艺', 'zongyi/?alt=json'))
    contentList.append(('体育', 'tiyu/?alt=json'))
    contentList.append(('新闻', 'xinwen/?alt=json'))
    contentList.append(('卡通', 'katong/?alt=json'))
    return contentList
def printfile(str):
    pass

def dosearch():
    result=''
    keyboard =xbmc.Keyboard('','请输入搜索内容')
    xbmc.sleep( 1500 )
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        keyword = keyboard.getText()
        p_url='http://allchinesetv.com/search/?q=%s&alt=json'%keyword
        pageData = getPageData(p_url)
        json_response = simplejson.loads(pageData)
        for item in json_response:
            listitem = xbmcgui.ListItem( item['title'],thumbnailImage=item['image'] )
            nextURL = sys.argv[0] + item['link']
            printfile(nextURL)
            xbmcplugin.addDirectoryItem(handle, nextURL, listitem, True)
    else: return

## Entrance point:
rootURL = 'http://allchinesetv.com/'
youtubeURL = 'plugin://plugin.video.youtube/?action=play_video&autoplay=1&videoid=%s'
handle = int(sys.argv[1])
mode = 0
isFolder = True
# Get parameters
if sys.argv[2] != '':
    printfile( "DEBUGGING sys.argv[0] = " + sys.argv[0] + ",    sys.argv[1] = " + sys.argv[1] + ",    sys.argv[2] = " + sys.argv[2])
    paraList = sys.argv[2][1:].replace('%2f', '/').replace('%3f', '?').replace('%3d', '=').split('&', 1)
    # Right now there are only two kinds of parameters: dirLevel (single digit number)
    # and the URL
    for item in paraList:
        if len(item) == 1 and item != '/':
            mode = int(item);
        else:
            pageURL = item.replace('%26', '&')

    if mode < 2:
        pageURL = rootURL + pageURL
    else:
        pageURL=youtubeURL%pageURL

    printfile( "mode: " + str(mode) + ", pageURL: " + pageURL)

menu = []
itemNumber = 1

if mode == 0:
    printfile( 'main level')
    pageData = getPageData(rootURL)
    menu=getMainMenu(pageData)
    listitem = xbmcgui.ListItem('[COLOR F0F0F0F0] 拼音汉字搜索:[/COLOR][COLOR FF00FF00]【点此进入】[/COLOR]')
    nexturl=sys.argv[0] + '?3&search'
    printfile(nexturl)
    xbmcplugin.addDirectoryItem(handle,nexturl,  listitem, True)
    for menuItem in menu:
        listitem = xbmcgui.ListItem( menuItem[0] )
        nexturl=sys.argv[0] + '?1&' + menuItem[1]
        printfile(nexturl)
        xbmcplugin.addDirectoryItem(handle,nexturl,  listitem, True)
elif mode == 1:
    # Check if it has sub-categories on the left side of the page
    pageData = getPageData(pageURL)
    json_response = simplejson.loads(pageData)
    for item in json_response:
        if len(item['image'])>0:
            listitem = xbmcgui.ListItem( item['title'],thumbnailImage=item['image'] )
        else:
            listitem = xbmcgui.ListItem( item['title'])

        nextURL = sys.argv[0] + item['link']
        printfile(nextURL)
        xbmcplugin.addDirectoryItem(handle, nextURL, listitem,item['dir'] )
elif mode == 2:
    xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(pageURL)

elif mode == 3:
    dosearch()
elif mode == 5:
    xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(pageURL)
xbmc.executebuiltin("Container.SetViewMode(500)")
xbmcplugin.endOfDirectory(handle)